#!/usr/bin/python
#coding=gbk

import sys
import os

try:
    sys.path.append('/mnt/jiuqian_tools/lib/')
except:
    pass

currentDir = os.path.dirname(__file__)
import json
from collections import OrderedDict
from PySide2 import QtGui, QtWidgets, QtCore


class FolderFinder(QtWidgets.QSystemTrayIcon):
    def __init__(self, parent=None):
        super(FolderFinder, self).__init__(parent)
        self.setIcon(QtGui.QIcon(os.path.join(os.path.abspath(currentDir), 'ff.png')))
        self.show()

        trayIconMenu = QtWidgets.QMenu(parent)
        quitAction = trayIconMenu.addAction('&Quit')
        self.setContextMenu(trayIconMenu)


        self.activated.connect(self.onTrayIconActived)
        quitAction.triggered.connect(self.onQuitTriggered)

    def onTrayIconActived(self, reason):
        if reason == QtWidgets.QSystemTrayIcon.Trigger:
            pos = QtGui.QCursor.pos()
            self.win = FolderFinderUI(pos)
            self.win.show()

    def onQuitTriggered(self):
        QtCore.QCoreApplication.exit()


class FolderFinderUI(QtWidgets.QWidget):
    ''' Custom a popup window
    Parameters
    ----------
    pos:    PySide2.QtCore.QPoint
        The position of cursor
    '''
    def __init__(self, pos, parent=None):
        super(FolderFinderUI, self).__init__(parent)
        self.setWindowFlags(QtCore.Qt.Popup)
        # self.setStyleSheet('QWidget{background-color: rgb(60,60,60);color:rgb(220,220,220)}')
        self.setLayout(QtWidgets.QVBoxLayout())
        self.layout().setContentsMargins(0,0,0,0)
        self.move(pos)

        self.init()

    def init(self):
        self.comboBox = QtWidgets.QComboBox()
        self.comboBox.addItem('LRC')

        self.listWidget = QtWidgets.QListWidget()
        self.listWidget.setAlternatingRowColors(True)
        self.listWidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

        self.layout().addWidget(self.comboBox)
        self.layout().addWidget(self.listWidget)

        self.update()

    def update(self):
        self.listWidget.clear()

        jfile = os.path.abspath(os.path.join(currentDir, 'global.json'))

        with open(jfile, 'r') as hd:
            data = json.load(hd, object_pairs_hook=OrderedDict)

        for key, value in data.items():
            item = ButtonItem(key, value)
            self.listWidget.addItem(item)
            self.listWidget.setItemWidget(item, item.button)


class ButtonItem(QtWidgets.QListWidgetItem):
    def __init__(self, path, desc):
        super(ButtonItem, self).__init__()
        self.setSizeHint(QtCore.QSize(self.sizeHint().width(), 25))

        self.setText(desc)

        self.button = QtWidgets.QPushButton(desc)
        self.button.setIcon(self.button.style().standardIcon(QtWidgets.QStyle.SP_FileDialogNewFolder))
        self.button.setStyleSheet('QPushButton{text-align:left;}')
        self.setData(QtCore.Qt.DisplayRole, path)

        self.button.clicked.connect(self.onButtonClicked)

    def button(self):
        return self.button

    def onButtonClicked(self):
        import webbrowser
        webbrowser.open(self.data(QtCore.Qt.DisplayRole))

def pname_exists(inp):
    import commands
    proc = commands.getoutput('ps -ef | grep {} | grep -v grep'.format(inp))
    return True if proc.count('python {}'.format(inp)) > 1 else False

if __name__ == '__main__':
    base_name = os.path.basename(__file__)

    if not pname_exists(base_name):
        app = QtWidgets.QApplication(sys.argv)
        main_ui = FolderFinder()
        sys.exit(app.exec_())
    else:
        print '{} is running.'.format(base_name)





